/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.pacs.websocket;

import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

import java.util.concurrent.BlockingQueue;

/**
 *
 * @author Administrator
 */
public class MsgService extends Thread {

    Gson gson = new Gson();
    private BlockingQueue sendMessageQueue;//发送消息的队列
    private StartServer mws;

    private Message msg;
    private boolean flag = true;

    public MsgService(StartServer mws) {
        this.mws = mws;
        sendMessageQueue = mws.getSendQueue();
    }

    @Override
    public void run() {
        System.out.println("启动发送消息线程---------");
        Gson gson = new Gson();
        while (isFlag()) {
            try {

                msg = (Message) mws.getSendQueue().take();
              
               
                    handlerMsg(msg);
                
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        System.out.println("结束发送消息线程 ---------");
    }

    public void handlerMsg(Message msg) {
       if(msg.getTo()!=null&&msg.getFrom()!=null&&mws.getNameMap().get(msg.getTo())!=null){
        mws.send(mws.getNameMap().get(msg.getTo()).channel(), gson.toJson(msg));
       }
        
    }

    public void sendToAll(Message msg) {

      
    }

    /**
     * @return the flag
     */
    public boolean isFlag() {
        return flag;
    }

    /**
     * @param flag the flag to set
     */
    public void setFlag(boolean flag) {
        this.flag = flag;
    }
    
   
}
